import type { AxiosRequestConfig, AxiosInstance, AxiosResponse, InternalAxiosRequestConfig, AxiosError } from 'axios';
import type { Result } from '/#/axios';
import axios from 'axios';

export class Vaxios {
    // 静态实例属性
    private axiosInstance: AxiosInstance;
    constructor(config: AxiosRequestConfig) {
        this.axiosInstance = axios.create(config);
        // 拦截器
        this.setupInterceptors()
    }

    request<T = any>(config: AxiosRequestConfig): Promise<T> {
        return new Promise((resolve, reject) => {
            this.axiosInstance.request<any, AxiosResponse>(config)
                .then((res: AxiosResponse<Result>) => {
                    resolve(res.data as unknown as Promise<T>);
                })
                .catch((e: Error | AxiosError) => {
                    if (axios.isAxiosError(e)) {
                        // 在此处重写来自axios的错误消息
                    }
                    reject(e);
                });
        })
    }

    get<T = any>(config: AxiosRequestConfig): Promise<T> {
        return this.request({ ...config, method: 'GET' });
    }

    post<T = any>(config: AxiosRequestConfig): Promise<T> {
        return this.request({ ...config, method: 'POST' });
    }

    put<T = any>(config: AxiosRequestConfig): Promise<T> {
        return this.request({ ...config, method: 'PUT' });
    }

    delete<T = any>(config: AxiosRequestConfig): Promise<T> {
        return this.request({ ...config, method: 'DELETE' });
    }

    // 拦截器配置
    private setupInterceptors() {
        this.axiosInstance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
            return config;
        }, undefined);
        this.axiosInstance.interceptors.response.use((res: AxiosResponse<any>) => {
            return res;
        }, undefined);
    }
}